package com.utils;

import com.bean.other.TableBack;
import com.config.Commons;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;

import java.io.File;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Component
public class DbUtil {

    @Autowired
    private Commons commons;

    @Autowired
    private ExcelUtil excelUtil;

    @Autowired
    private ApplicationContext applicationContext;

    public Object getBean(Class cla){
        return applicationContext.getBean(cla);
    }

    @Value("${easyexcel.outpath}")
    private String easyexcelOut;

    public void DbBack() throws ClassNotFoundException {
        List<TableBack> list = commons.getTableBackList();
        String outPath = easyexcelOut + "/back";
        File backOut = new File(outPath);
        if(backOut.exists()){
            if (backOut.isDirectory()) {
                // 获取文件夹内的所有文件和子目录
                File[] files = backOut.listFiles();
                if (files != null) {
                    for (File file : files) {
                        file.delete();  // 删除文件
                    }
                }
            }
        }
        for(TableBack tableBack : list){
            String className = tableBack.getClassName();
            String jpaBeanName = tableBack.getJpaBeanName();
            Class cla = Class.forName(className);
            Class claJpa = Class.forName(jpaBeanName);
            JpaRepository obj = (JpaRepository) applicationContext.getBean(claJpa);

            List data = obj.findAll();
            System.out.println(data.size());

            excelUtil.SimpleWrite(outPath,tableBack.getContent()+LocalDate.now().toString(),cla,"test",data);
        }
    }

}
